package com.example.springboot_07_upload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @auther cangshufeilun
 * @date 2022/4/3 14:29
 */
@Controller

public class UploadController {

    final  static String UPLOADED_FOLDER = "./upload/";

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "result";
    }

    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile file,  RedirectAttributes redirectAttributes) {


        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            // UPLOADED_FOLDER 文件本地存储地址
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            redirectAttributes.addFlashAttribute("message", "success uploaded");

        } catch (IOException e) {

            redirectAttributes.addFlashAttribute("message", "fail uploaded"+e.getMessage());
            e.printStackTrace();
        }
        return "redirect:/uploadStatus";
    }

    @GetMapping("/more")
    public String uploadMore() {
        return "uploadMore";
    }

    @PostMapping("/uploadMore")
    public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
                                 RedirectAttributes redirectAttributes) {

        for(MultipartFile file:files){
            try {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);
                redirectAttributes.addFlashAttribute("message", "success uploaded all");

            } catch (IOException e) {
                redirectAttributes.addFlashAttribute("message", "fail uploaded all");
                e.printStackTrace();
            }
        }

        return "redirect:/uploadStatus";
    }

}
